<!--
 * @Author: chengjiang
 * @Date: 2024-11-06 11:18:37
 * @Description: 
-->
<template>
    <div>
        <div>
            <TitleHeader val="价格管理" />
            <GoldTable :pageType="pageType" />
        </div>
        <div>
            <TitleHeader val="资源配置" />
            <Photo :pageType="pageType" />
        </div>
        <div class="mb-10">
            <TitleHeader val="信息设置" />
            <!-- 页脚信息列表 -->
            <Footer :pageType="pageType" />
        </div>
        <div v-if="ifSee">
            <TitleHeader val="开闭盘" />
            <a-flex class="mb-10" justify="space-around" align="center">
                <div>
                    状态：
                    <a-radio-group v-model:value="value">
                        <a-radio :value="1">开盘</a-radio>
                        <a-radio :value="0">闭盘</a-radio>
                    </a-radio-group>
                </div>
                <div>
                    <a-flex align="center">
                        <p class="w-40 underline-dark-50">作用时间：</p>
                        <a-input-number :min="0" :max="99999" :step="1" v-model:value.lazy="hour" autofocus placeholder="输入小时" size="large" />
                        <p class="ml-5">h</p>
                    </a-flex>
                </div>
                <a-flex justify="flex-end" align="center">
                    <a-popconfirm title="确认提交吗？" @confirm="save">
                        <a-button type="primary" class="editable-add-btn mr-5">提交</a-button>
                    </a-popconfirm>
                    <a-popconfirm title="确认重置吗？" @confirm="reload">
                        <a-button class="editable-add-btn mr-5">重置</a-button>
                    </a-popconfirm>
                </a-flex>
                <div><p>上一次更新时间：{{ updateTime }}</p></div>
                <div>
                    <a-flex align="center">
                        <p class="underline-dark-50">倒计时：</p>
                        <p class="text-red-600">{{ formattedTime }}</p>
                    </a-flex>
                </div>
            </a-flex>
        </div>
    </div>
</template>

<script lang="ts" setup>
import TitleHeader from '../../components/TitleHeader.vue'
import {OpenClose, GetOpenClose} from '../../api/home'
import Footer from './gold/footer.vue'
import GoldTable from './gold/GoldTable.vue'
import Photo from './gold/Photo.vue'
import { ref, watch, computed, onMounted } from 'vue';
import { PAGE_TYPE_Customer } from '../../enums/const'
import { useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
const route = useRoute();
const ifSee = ref(false);
const value = ref<number>(1);
const hour = ref<number | null>(null);
const isCounting = ref(false);
const timeRemaining = ref(0);
const pageType = ref<number>(PAGE_TYPE_Customer)
console.log('route.params.priceType', route.params.priceType)
if (typeof route.params.priceType === 'string') {
    pageType.value = Number(route.params.priceType)
}
const updateTime = ref<string>('2024-11-19 14:20:00');
    let intervalId: any = null;

/**
 * @description - startCountdown: 开闭盘上次更新的时间进行倒计时，不传，则默认从当前时间进行倒计时
 * @param timeStr  格式：YYYY-MM-DD HH:mm:ss
 * @returns
 */
const startCountdown = (timeStr?: string) => {
    if (hour.value === null || hour.value <= 0) {
        isCounting.value = false;
        return;
    }
    let endTime: number;
    const now = new Date().getTime();
    if (timeStr) {
        endTime = new Date(timeStr).getTime() + hour.value! * 3600 * 1000
    }else {
        endTime = new Date().getTime() + hour.value! * 3600 * 1000
    }
    if (endTime - now <= 0) {
        isCounting.value = false;
        return;
    }
    isCounting.value = true;
    timeRemaining.value = endTime - now; // 将小时转换为毫秒

    if (intervalId) {
        clearInterval(intervalId);
    }

    intervalId = setInterval(() => {
        timeRemaining.value -= 1000;

        if (timeRemaining.value <= 0) {
            clearInterval(intervalId);
            isCounting.value = false;
        }
    }, 1000);
};
GetOpenClose().then((res)=>{
      hour.value = res.data.effectHour
      value.value = res.data.status
      updateTime.value = res.data.updateTime as string
      startCountdown(updateTime.value);
    }).catch(()=>{
      message.error('获取开闭盘数据失败')
    })
// 监听路由
// 获取当前路由。
watch(() => route.path, () => {
    console.log('route changed: ', route.path)
    ifSee.value = false;
    if (typeof route.params.priceType === 'string') {
        pageType.value = Number(route.params.priceType)
        if (pageType.value === 0 ) {
            ifSee.value = true;
            startCountdown(updateTime.value);
        }
    }
})
const save = () => {
    OpenClose({
        id: 0,
        status: value.value,
        effectHour: hour.value as number,
    }).then(()=>{
      message.success('保存开闭盘数据成功')
    }).catch(()=>{
      message.error('保存开闭盘失败')
    })
    // 重新获取
    GetOpenClose().then((res)=>{
      hour.value = res.data.effectHour
      value.value = res.data.status
      updateTime.value = res.data.updateTime as string
    }).catch(()=>{
      message.error('获取开闭盘数据失败')
    })
    startCountdown(updateTime.value);
}
const reload = () => {
    hour.value = 0
    value.value = 1
    OpenClose({
        id: 0,
        status: value.value,
        effectHour: hour.value as number,
    }).then((res)=>{
      console.log(res)
      message.success('保存开闭盘数据成功')
    }).catch(()=>{
      message.error('保存开闭盘失败')
    })
}
const formattedTime = computed(() => {
    const totalSeconds = Math.floor(timeRemaining.value / 1000);
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;

    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
});
// 
onMounted(() => {
    console.log('route changed: ', route.path)
    ifSee.value = false;
    if (typeof route.params.priceType === 'string') {
        pageType.value = Number(route.params.priceType)
        if (pageType.value === 0 ) {
            ifSee.value = true;
            startCountdown(updateTime.value);
        }
    }
});
</script>